package com.hbnu.tonghengchang;

import java.io.*;
import java.net.*;
import java.util.concurrent.*;

public class MultPic {
    private static final int PORT = 8890;
    private static final ExecutorService pool = Executors.newCachedThreadPool();

    // 并发图片服务器
    public static void startConcurrentServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("并发图片服务器启动...");

        while (true) {
            Socket socket = serverSocket.accept();
            pool.execute(() -> handleConcurrentUpload(socket));
        }
    }

    private static void handleConcurrentUpload(Socket socket) {
        String clientInfo = socket.getInetAddress() + ":" + socket.getPort();
        System.out.println("客户端连接: " + clientInfo);

        try (DataInputStream dis = new DataInputStream(socket.getInputStream())) {
            String imageName = dis.readUTF();
            long fileSize = dis.readLong();

            // 为每个客户端创建独立目录
            File clientDir = new File("uploads_" + clientInfo.replace(":", "_"));
            clientDir.mkdirs();

            try (FileOutputStream fos = new FileOutputStream(new File(clientDir, imageName))) {
                byte[] buffer = new byte[8192];
                int read;
                long remaining = fileSize;

                while (remaining > 0 && (read = dis.read(buffer, 0, (int)Math.min(buffer.length, remaining))) != -1) {
                    fos.write(buffer, 0, read);
                    remaining -= read;
                }
            }
            System.out.println("并发上传完成: " + imageName + " from " + clientInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 并发客户端 - 模拟多个客户端同时上传
    public static void startConcurrentClients(int clientCount) {
        for (int i = 0; i < clientCount; i++) {
            final int clientId = i;
            pool.execute(() -> {
                try {
                    uploadConcurrentImage("image" + clientId + ".jpg");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private static void uploadConcurrentImage(String imageName) throws IOException {
        Socket socket = new Socket("localhost", PORT);

        try (DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
             ByteArrayInputStream bis = new ByteArrayInputStream(createMockImageData())) {

            dos.writeUTF(imageName);
            dos.writeLong(1024); // 模拟1KB图片数据

            byte[] buffer = new byte[1024];
            int read;
            while ((read = bis.read(buffer)) != -1) {
                dos.write(buffer, 0, read);
            }
            dos.flush();
        }
        System.out.println("并发客户端发送: " + imageName);
    }

    // 生成模拟图片数据
    private static byte[] createMockImageData() {
        byte[] data = new byte[1024];
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte)(i % 256);
        }
        return data;
    }

    public static void main(String[] args) throws IOException {
        if (args.length > 0 && "server".equals(args[0])) {
            startConcurrentServer();
        } else {
            startConcurrentClients(5); // 启动5个并发客户端
        }
    }
}